package com.github.florent37.mylittlecanvas.touch.actions;

import com.github.florent37.mylittlecanvas.shape.Shape;
import com.github.florent37.mylittlecanvas.touch.EventPos;
import ohos.agp.components.Component;
import ohos.multimodalinput.event.TouchEvent;

public abstract class MoveAction<S extends Shape, POS> {
    protected final S shape;
    protected final POS pos;
    private final EventPos event_pos;

    public MoveAction(EventPos event_pos, S shape, POS pos) {
        this.event_pos = event_pos;
        this.shape = shape;
        this.pos = pos;
    }

    public final void move(TouchEvent event, Component component) {
        switch (event_pos) {
            case X:
                move(getTouchX(event, 0, component));
                break;
            case Y:
                move(getTouchY(event, 0, component));
                break;
        }
    }

    protected abstract void move(float value);

    private float getTouchX(TouchEvent touchEvent, int index, Component component) {
        float touchX = 0;
        if (touchEvent.getPointerCount() > index) {
            int[] xy = component.getLocationOnScreen();
            if (xy != null && xy.length == 2) {
                touchX = touchEvent.getPointerScreenPosition(index).getX() - xy[0];
            } else {
                touchX = touchEvent.getPointerPosition(index).getX();
            }
        }
        return touchX;
    }

    private float getTouchY(TouchEvent touchEvent, int index, Component component) {
        float touchY = 0;
        if (touchEvent.getPointerCount() > index) {
            int[] xy = component.getLocationOnScreen();
            if (xy != null && xy.length == 2) {
                touchY = touchEvent.getPointerScreenPosition(index).getY() - xy[1];
            } else {
                touchY = touchEvent.getPointerPosition(index).getY();
            }
        }
        return touchY;
    }
}
